{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch  \n",
    "import torch.optim as optim  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建输入数据和目标数据  \n",
    "x = torch.randn(100, 1)  \n",
    "y = 3 * x + 2 + torch.randn(100, 1)  # 真实参数为3和2  \n",
    "  \n",
    "# 模型参数  \n",
    "w = torch.randn(1, requires_grad=True)  \n",
    "b = torch.randn(1, requires_grad=True)  \n",
    "\n",
    "# 优化器  \n",
    "optimizer = optim.SGD([w, b], lr=0.01)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Tensor"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/anaconda3/envs/science39/lib/python3.9/site-packages/torch/autograd/__init__.py:266: UserWarning: CUDA initialization: The NVIDIA driver on your system is too old (found version 10020). Please update your GPU driver by downloading and installing a new version from the URL: http://www.nvidia.com/Download/index.aspx Alternatively, go to: https://pytorch.org to install a PyTorch version that has been compiled with your version of the CUDA driver. (Triggered internally at ../c10/cuda/CUDAFunctions.cpp:108.)\n",
      "  Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0, Loss: 16.2206974029541\n",
      "Epoch 100, Loss: 1.3535367250442505\n",
      "Epoch 200, Loss: 0.9218542575836182\n",
      "Epoch 300, Loss: 0.9056078195571899\n",
      "Epoch 400, Loss: 0.9048884510993958\n",
      "Epoch 500, Loss: 0.9048541784286499\n",
      "Epoch 600, Loss: 0.9048525094985962\n",
      "Epoch 700, Loss: 0.9048524498939514\n",
      "Epoch 800, Loss: 0.9048524498939514\n",
      "Epoch 900, Loss: 0.9048523902893066\n",
      "Learned parameters: w = 2.9411587715148926, b = 1.913278341293335\n"
     ]
    }
   ],
   "source": [
    "# 训练模型  \n",
    "for epoch in range(1000):  \n",
    "    model = x * w + b  \n",
    "    loss = ((model - y) ** 2).mean()  \n",
    "      \n",
    "    optimizer.zero_grad()  \n",
    "    loss.backward()  \n",
    "    optimizer.step()  \n",
    "  \n",
    "    if epoch % 100 == 0:  \n",
    "        print(f'Epoch {epoch}, Loss: {loss.item()}')  \n",
    "  \n",
    "print(f'Learned parameters: w = {w.item()}, b = {b.item()}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用Torch.nn的方式重写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch  \n",
    "import torch.nn as nn  \n",
    "import torch.optim as optim  \n",
    "  \n",
    "# 定义模型  \n",
    "class LinearRegressionModel(nn.Module):  \n",
    "    def __init__(self):  \n",
    "        super(LinearRegressionModel, self).__init__()  \n",
    "        self.linear = nn.Linear(1, 1)  # 输入和输出特征的数量都为1  \n",
    "  \n",
    "    def forward(self, x):  \n",
    "        return self.linear(x)  \n",
    "  \n",
    "# 创建模型实例  \n",
    "model = LinearRegressionModel()  \n",
    "  \n",
    "# 创建输入数据和目标数据  \n",
    "x = torch.randn(100, 1)  \n",
    "y = 3 * x + 2 + torch.randn(100, 1)  \n",
    "  \n",
    "# 定义损失函数  \n",
    "criterion = nn.MSELoss()  \n",
    "  \n",
    "# 定义优化器  \n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)  \n",
    "  \n",
    "# 训练模型  \n",
    "for epoch in range(1000):  \n",
    "    # 前向传播：计算预测值和损失  \n",
    "    y_pred = model(x)  \n",
    "    loss = criterion(y_pred, y)  \n",
    "  \n",
    "    # 反向传播：计算梯度  \n",
    "    optimizer.zero_grad()  \n",
    "    loss.backward()  \n",
    "  \n",
    "    # 更新参数  \n",
    "    optimizer.step()  \n",
    "  \n",
    "    # 打印损失（可选）  \n",
    "    if epoch % 100 == 0:  \n",
    "        print(f'Epoch {epoch}, Loss: {loss.item()}')  \n",
    "  \n",
    "# 获取训练后的参数  \n",
    "w, b = model.parameters()  \n",
    "print(f'Learned parameters: w = {w.item()}, b = {b.item()}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "science39",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
